package ch1.threadlocal;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 类说明：ThreadLocal造成的内存泄漏演示
 */
public class ThreadLocalOOM {
    //静态常量，在主线程里面表示500个线程任务
    private static final int TASK_LOOP_SIZE = 500;

    //定义一个线程池，里面有5个线程在跑
    final static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 5, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>());

    final static ThreadLocal<LocalVariable> localVariable= new ThreadLocal<>();

    //定义一个类，类里面有个成员变量，成员变量是5M大小的字节数组
    private static class LocalVariable {
        private byte[] a = new byte[5 * 1024 * 1024];
    }

    public static void main(String[] args) throws InterruptedException {
        Object o = new Object();
        //执行500个线程任务，每个线程任务是创建字节数组
        for (int i = 0; i < TASK_LOOP_SIZE; ++i) {
            poolExecutor.execute(new Runnable() {
                public void run() {
//                    new LocalVariable();  //创建字节数组
                    localVariable.set(new LocalVariable());
                    System.out.println("use local varaible");
                    //localVariable.remove();
                }
            });

            Thread.sleep(100);
        }
        System.out.println("pool execute over");
    }

}
